import { reactive, toValue, type Reactive } from "vue";
import { Http } from "../base/http";
import type { interForm } from "../base/type";

export class ListSearch<T extends Record<string, any>> extends Http {
    data = reactive({} as T)
    size: string = "small";
    labels = reactive({} as { [key in keyof T & string]?: interForm<T, key> });
    reactiveProp: (keyof T)[] = []
    constructor() {
        super()
        this.setData({} as T)
    }
    setData(data: T) {
        let timer: number = 0
        //当数组中的查询条件发生变化时自动触发查询
        this.data = reactive(this.utils_proxy_set(data, (target, key) => {
            //防抖
            if (timer) clearTimeout(timer)
            timer = setTimeout(() => {
                if (this.reactiveProp.includes(key)) this.onSearch()
            }, 200);
        }))
    }
    /**
     * 获取当前查询条件
     * @param props 要返回的字段,不传返回全部
     */
    getData(props?: (keyof T)[]): { [key in keyof T]: T[key] } {
        const data = toValue(this.data)
        const target = {} as { [key in keyof T]: T[key] }
        Object.keys(data).forEach((key: keyof T) => {
            const item = data[key]
            if (item === undefined || item === '') return
            if (props && !props.includes(key)) return
            target[key] = data[key]
        })
        return target
    }
    defaultInputChange<U extends keyof T>(data: T, prop: U, value: T[U]) {
        data[prop] = value
    }
    showChange(value: boolean) {
        this.show = value
    }
    onSearch() {
        throw new Error("未设置查询函数");
    }
    onCancal() {
        this.data = reactive({} as T)
        this.onSearch()
    }
} 